package com.tuo.controller;

import com.tuo.beans.Customer;
import com.tuo.beans.Orders;
import com.tuo.service.CustomerService;
import com.tuo.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by tuo on 2016/1/9.
 */
@Controller
public class OrderController {
    @Autowired
    CustomerService customerService;
    @Autowired
    OrderService orderService;

    @ResponseBody
    @RequestMapping("order")
    public Map<String, Object> order(Orders orders, int page, int rows) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Orders> orderses = null;
        try {
            orderses = orderService.query(orders, true);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        map.put("total", orderses.size());
        List<Orders> list = new ArrayList<Orders>();
        for (int i = (page - 1) * rows; i < orderses.size() && i < (page * rows); i++) {
            list.add(orderses.get(i));
        }
        map.put("rows", list);
        return map;
    }

    @ResponseBody
    @RequestMapping("saveOrder")
    public Map<String, String> saveOrder(Orders orders) {
        Map<String, String> map = new HashMap<String, String>();
        try {
            Customer customer = this.customerService.get(orders.getCusId());
            orders.setCustomerName(customer.getName());
            this.orderService.save(orders);
            map.put("message", "success");
        } catch (Throwable e) {
            e.printStackTrace();
            map.put("errorMsg", e.getMessage());
        }
        return map;
    }

    @ResponseBody
    @RequestMapping("editOrder")
    public Map<String, String> editOrder(Orders orders) {
        Map<String, String> map = new HashMap<String, String>();
        try {
            this.orderService.update(orders);
            map.put("message", "success");
        } catch (Throwable e) {
            map.put("errorMsg", e.getMessage());
        }
        return map;
    }
}
